package com.tuozixuan;

import java.util.HashMap;
import java.util.Map;

import redis.clients.jedis.JedisPooled;
import redis.clients.jedis.search.IndexDefinition;
import redis.clients.jedis.search.IndexOptions;
import redis.clients.jedis.search.Query;
import redis.clients.jedis.search.RediSearchUtil;
import redis.clients.jedis.search.Schema;
import redis.clients.jedis.search.SearchResult;

/**
 * https://github.com/redis/jedis/blob/master/docs/redisearch.md
 */
public class RedisSearchDemo {

	public static void main(String[] args) {

		JedisPooled client = new JedisPooled("192.168.101.81", 6379);

		// 创建索引
		Schema schema = new Schema().addTextField("title", 5.0).addTextField("body", 1.0).addNumericField("price");
		IndexDefinition def = new IndexDefinition().setPrefixes(new String[] { "item:", "product:" })
				.setFilter("@price>100");
		client.ftCreate("item-index", IndexOptions.defaultOptions().setDefinition(def), schema);

		// 添加数据
		Map<String, Object> fields = new HashMap<>();
		fields.put("title", "hello world");
		fields.put("body", "lorem ipsum");
		fields.put("price", 1337);
		client.hset("item:hw", RediSearchUtil.toStringMap(fields));

		// 创建查询对象
		Query query = new Query("hello world").addFilter(new Query.NumericFilter("price", 0, 2000)).limit(0, 5);

		// 执行查询
		SearchResult searchResult = client.ftSearch("item-index", query);
		System.out.println(searchResult.getDocuments());

		// 删除索引
		client.ftDropIndex("item-index");

		client.close();
	}

}
